package com.sailing.xjpb.ipaas.client.core;

import com.sailing.xjpb.common.web.WebUtils;
import com.sailing.xjpb.ipaas.client.common.IpaasClientConstants;
import com.sailing.xjpb.ipaas.client.common.UserInfoDecoder;
import com.sailing.xjpb.ipaas.client.entity.dto.SipUserCurrentInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 根据url拦截配置，获取用户票据信息并绑定到{@linkplain UserContext}。
 *
 * @author YW
 */
@Slf4j
public class IpaasSsoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        log.info(" init IpaasSsoFilter ");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            // 绑定用户相关信息
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            initUserContext(request);
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 清理上下文资源
            UserContext.clean();
        }
    }

    private void initUserContext(HttpServletRequest request) {

        String headerIpaasSessionId = request.getHeader(IpaasClientConstants.IPAAS_SESSION_ID);
        String paramIpaasSessionId = request.getParameter(IpaasClientConstants.IPAAS_SESSION_ID);
        UserContext.setIpaasSessionId(headerIpaasSessionId != null ? headerIpaasSessionId : paramIpaasSessionId);

        String headerAuthorization = request.getHeader(IpaasClientConstants.AUTHORIZATION);
        String paramAuthorization = request.getParameter(IpaasClientConstants.AUTHORIZATION);
        UserContext.setAuthorization(headerAuthorization != null ? headerAuthorization : paramAuthorization);

        String ipAddress = WebUtils.getIpAddress(request);
        UserContext.setIpAddress(ipAddress);

        // 设置当前用户信息
        setCurrentUser(request);

        // 设置租户信息
        String headerTenantCode = request.getHeader(IpaasClientConstants.HEADER_TENANT_CODE);
        String paramTenantCode = request.getParameter(IpaasClientConstants.HEADER_TENANT_CODE);
        String tenantCode = StringUtils.isNotBlank(headerTenantCode) ? headerTenantCode : paramTenantCode;
        if (StringUtils.isBlank(tenantCode) && StringUtils.isNotBlank(UserContext.getAuthorization())) {
            try {
                SipUserCurrentInfoDTO sipUserCurrentInfoDTO = UserContext.currentUser();
                tenantCode = sipUserCurrentInfoDTO.getTenantCode();
            } catch (Exception e) {
                log.warn("获取租户信息出错：token = {}, 错误信息：{}", UserContext.getAuthorization(), e.getMessage());
            }
        }
        UserContext.setUserTenantCode(tenantCode);
    }

    private void setCurrentUser(HttpServletRequest request) {
        String encodeUserInfo = request.getHeader(IpaasClientConstants.CURRENT_USER_INFO);
        if (encodeUserInfo == null) {
            return;
        }
        try {
            String key = request.getHeader(IpaasClientConstants.ENCODE_KEY);
            SipUserCurrentInfoDTO currentUser = UserInfoDecoder.decode(key, encodeUserInfo);
            UserContext.setCurrentUser(currentUser);
            log.info("拦截到用户信息：token={}, userId={}", UserContext.getAuthorization(), currentUser.getUserid());
        } catch (Exception e) {
            log.warn("token={}，用户信息解密失败：{}", UserContext.getAuthorization(), encodeUserInfo, e);
        }
    }

    @Override
    public void destroy() {
        log.info(" destroy IpaasSsoFilter ");
    }

}
